<template>
  <div class="application-manage">
    <TopBar />

    <div class="content">
      <MenuLine />

      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog" :icon="Plus">添加申请</el-button>
      </div>

      <el-table :data="applicationList" style="width: 100%" border v-loading="applicationStore.loading">
        <el-table-column prop="id" label="ID" width="80" align="center"/>
        <el-table-column prop="materialName" label="物资名称" min-width="150" show-overflow-tooltip/>
        <el-table-column prop="quantity" label="申请数量" width="100" align="center"/>
        <el-table-column prop="applyReason" label="申请原因" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="applicantName" label="申请人" width="120" align="center"/>
        <el-table-column prop="createTime" label="申请时间" width="170" align="center"/>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewerName" label="审核人" width="120" align="center">
           <template #default="{ row }">
             {{ row.reviewerName || '-' }}
           </template>
        </el-table-column>
         <el-table-column prop="reviewTime" label="审核时间" width="170" align="center">
           <template #default="{ row }">
             {{ row.reviewTime || '-' }}
           </template>
        </el-table-column>
         <el-table-column prop="reviewComments" label="审核意见" min-width="180" show-overflow-tooltip/>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="openEditDialog(row)"
              :disabled="row.status !== '待审核'"
              :icon="Edit"
            >编辑</el-button>
            <el-button
              type="success"
              size="small"
              @click="openReviewDialog(row)"
              :disabled="row.status !== '待审核'"
              :icon="Check"
            >审核</el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteApplication(row.id, row.status)"
              :disabled="row.status !== '待审核'"
              :icon="Delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        :title="dialogTitle"
        v-model="formDialogVisible"
        width="45%"
        @close="resetForm"
        :close-on-click-modal="false"
      >
        <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
          <el-form-item v-if="isAdmin" label="申请员工" prop="applicantId">
             <el-select
                v-model="form.applicantId"
                placeholder="请选择申请员工"
                filterable
                clearable
                style="width: 100%"
                :loading="loadingUsers"
              >
                <el-option
                  v-for="user in employeeOptions"
                  :key="user.id"
                  :label="user.realName"
                  :value="user.id"
                />
                <el-option v-if="!employeeOptions.length && !loadingUsers" disabled label="无可用员工" :value="null" />
             </el-select>
          </el-form-item>

          <el-form-item label="申请物资" prop="materialId">
             <el-select
                v-model="form.materialId"
                placeholder="请选择申请物资"
                filterable
                clearable
                style="width: 100%"
                :loading="loadingMaterials"
              >
                <el-option
                  v-for="material in materialOptions"
                  :key="material.id"
                  :label="`${material.name} (库存: ${material.quantity})`"
                  :value="material.id"
                  :disabled="material.quantity <= 0 && !isEdit"
                />
                 <el-option v-if="!materialOptions.length && !loadingMaterials" disabled label="无可用物资" :value="null" />
             </el-select>
          </el-form-item>

          <el-form-item label="申请数量" prop="quantity">
            <el-input-number v-model="form.quantity" :min="1" placeholder="请输入申请数量" style="width: 100%;" />
          </el-form-item>

          <el-form-item label="申请原因" prop="applyReason">
            <el-input
              v-model="form.applyReason"
              type="textarea"
              :rows="3"
              placeholder="请输入申请原因 (可选)"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="formDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>

       <el-dialog
        title="审核物资申请"
        v-model="reviewDialogVisible"
        width="40%"
        @close="resetReviewForm"
        :close-on-click-modal="false"
      >
        <el-descriptions v-if="currentApplication" :column="1" border style="margin-bottom: 20px;">
          <el-descriptions-item label="物资名称">{{ currentApplication.materialName }}</el-descriptions-item>
          <el-descriptions-item label="申请数量">{{ currentApplication.quantity }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentApplication.applicantName }}</el-descriptions-item>
          <el-descriptions-item label="申请原因">{{ currentApplication.applyReason || '-' }}</el-descriptions-item>
        </el-descriptions>
        <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="80px">
          <el-form-item label="审核结果" prop="status">
            <el-radio-group v-model="reviewForm.status">
              <el-radio label="通过">通过</el-radio>
              <el-radio label="未通过">未通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见" prop="reviewComments">
            <el-input
              v-model="reviewForm.reviewComments"
              type="textarea"
              :rows="3"
              placeholder="请输入审核意见 (可选)"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="reviewDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitReview">确定审核</el-button>
          </span>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue' // 引入 nextTick
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Check, Delete } from '@element-plus/icons-vue'
import { useApplicationStore, type MaterialApplication, type ApplicationCreatePayload, type ApplicationUpdatePayload, type ApplicationReviewPayload } from '@/stores/application'
import { useUserStore, type User } from '@/stores/user'
import { useMaterialStore, type Material } from '@/stores/material'
import TopBar from '@/components/TopBar.vue'
import MenuLine from '@/components/MenuLine.vue'

// --- Stores ---
const applicationStore = useApplicationStore()
const userStore = useUserStore()
const materialStore = useMaterialStore()

// --- State ---
const applicationList = ref<MaterialApplication[]>([])
const materialOptions = ref<Material[]>([]) // 用于下拉选择，包含库存
const employeeOptions = ref<User[]>([]) // 用于管理员选择申请人
const loadingUsers = ref(false)
const loadingMaterials = ref(false)

const formDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('添加申请')
const currentApplication = ref<MaterialApplication | null>(null) // 当前操作的申请

// --- Forms & Refs ---
const formRef = ref<FormInstance>()
const reviewFormRef = ref<FormInstance>()

const form = ref<ApplicationCreatePayload & { id?: number }>({ // 包含可选的 id 用于编辑
  materialId: null,
  quantity: 1, // 默认值
  applicantId: null,
  applyReason: '',
})

const reviewForm = ref<ApplicationReviewPayload>({
  id: 0,
  reviewerId: null,
  status: '',
  reviewComments: '',
})

// --- Computed ---
const isAdmin = computed(() => userStore.user?.role === 'MANAGER')
const currentUserId = computed(() => userStore.user?.id)

// --- Validation Rules ---
const formRules = computed<FormRules>(() => ({
  applicantId: [
    { required: isAdmin.value && !isEdit.value, message: '请选择申请员工', trigger: 'change' } // 编辑时申请人不可改，添加时管理员必选
  ],
  materialId: [
    { required: true, message: '请选择申请物资', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入申请数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '申请数量必须大于0', trigger: 'blur' }
    // 可以在提交时再加一层库存校验逻辑
  ],
  applyReason: [
    { max: 500, message: '申请原因长度不能超过500字符', trigger: 'blur' }
  ]
}))

const reviewRules: FormRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  reviewComments: [
    { max: 500, message: '审核意见长度不能超过500字符', trigger: 'blur' }
  ]
}

// --- Methods ---

// 获取申请列表
const fetchApplications = async () => {
  try {
    await applicationStore.fetchApplications()
    applicationList.value = applicationStore.applications
  } catch (error) {
    // Store 中已处理 ElMessage
    console.error("fetchApplications error:", error)
  }
}

// 获取物资选项
const fetchMaterials = async () => {
  loadingMaterials.value = true
  try {
    await materialStore.fetchMaterials()
    materialOptions.value = materialStore.materials
  } catch (error) {
    ElMessage.error('获取物资列表失败')
    materialOptions.value = []
  } finally {
    loadingMaterials.value = false
  }
}

// 获取员工选项 (仅管理员需要)
const fetchEmployees = async () => {
  if (!isAdmin.value) return // 非管理员无需加载
  loadingUsers.value = true
  try {
    await userStore.fetchUsers() // 假设 fetchUsers 返回所有用户
    // 筛选出角色为 EMPLOYEE 的用户
    employeeOptions.value = userStore.users.filter(user => user.role === 'EMPLOYEE')
  } catch (error) {
    ElMessage.error('获取员工列表失败')
    employeeOptions.value = []
  } finally {
    loadingUsers.value = false
  }
}

// 打开添加弹窗
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '添加物资申请'
  resetForm() // 重置表单
  form.value.applicantId = isAdmin.value ? null : currentUserId.value // 员工申请时自动填充ID
  formDialogVisible.value = true
  // 确保物资和员工列表已加载
  if (!materialOptions.value.length) fetchMaterials()
  if (isAdmin.value && !employeeOptions.value.length) fetchEmployees()
}

// 打开编辑弹窗
const openEditDialog = (row: MaterialApplication) => {
   if (row.status !== '待审核') {
     ElMessage.warning('只能编辑状态为 "待审核" 的申请')
     return
   }
  isEdit.value = true
  dialogTitle.value = '编辑物资申请'
  currentApplication.value = row // 记录当前行，用于比对库存等
  // 填充表单
  form.value = {
    id: row.id,
    materialId: row.materialId,
    quantity: row.quantity,
    applicantId: row.applicantId, // 保留原申请人ID，编辑时不允许修改申请人
    applyReason: row.applyReason || '',
  }
  formDialogVisible.value = true
  // 确保物资列表已加载
  if (!materialOptions.value.length) fetchMaterials()
  // 编辑时不需要加载员工列表，因为申请人不可改
}

// 打开审核弹窗
const openReviewDialog = (row: MaterialApplication) => {
   if (row.status !== '待审核') {
     ElMessage.warning('只能审核状态为 "待审核" 的申请')
     return
   }
   // 修改：确保在 DOM 更新后再显示对话框，并正确赋值
   currentApplication.value = null; // 先清空
   nextTick(() => {
       currentApplication.value = { ...row }; // 使用 nextTick 确保响应式更新
       resetReviewForm(); // 重置审核表单
       reviewForm.value.id = row.id;
       reviewForm.value.reviewerId = currentUserId.value; // 设置审核人为当前用户
       reviewDialogVisible.value = true;
   });

}

// 提交添加/编辑表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 客户端再次校验库存 (可选，后端已有校验)
      const selectedMaterial = materialOptions.value.find(m => m.id === form.value.materialId)
      if (!selectedMaterial) {
          ElMessage.error("未找到所选物资的信息，请刷新后重试");
          return;
      }

      let neededQuantity = form.value.quantity || 0;
      let availableStock = selectedMaterial.quantity;

      if (isEdit.value && currentApplication.value && currentApplication.value.materialId === form.value.materialId) {
          // 编辑状态，且物资未改变，可用库存应加上当前申请已占用的量
          availableStock += currentApplication.value.quantity;
      }

      if (neededQuantity > availableStock) {
          ElMessage.error(`物资 "${selectedMaterial.name}" 库存不足 (当前可用库存: ${availableStock})`);
          return;
      }


      // 准备 payload
      const payload = { ...form.value }
      // 确保 applicantId 正确设置
      if (!isEdit.value && !isAdmin.value) {
          payload.applicantId = currentUserId.value // 员工添加时 applicantId 是自己
      } else if (!isEdit.value && isAdmin.value && !payload.applicantId) {
           ElMessage.error("管理员添加申请时必须选择申请员工");
           return;
      } else if (isEdit.value && currentApplication.value) {
           // 编辑时不应改变申请人，从 currentApplication 获取原始申请人 ID
           payload.applicantId = currentApplication.value.applicantId;
      }


      try {
        if (isEdit.value && payload.id) { // 确保编辑时有 ID
           // 编辑操作需要传递 ID
           const updatePayload: ApplicationUpdatePayload = {
               id: payload.id,
               materialId: payload.materialId,
               quantity: payload.quantity,
               applyReason: payload.applyReason
           }
          await applicationStore.updateApplication(updatePayload)
          ElMessage.success('申请更新成功')
        } else if (!isEdit.value) { // 确保是创建操作
          // 创建操作
           const createPayload: ApplicationCreatePayload = {
               materialId: payload.materialId,
               quantity: payload.quantity,
               applicantId: payload.applicantId, // ID 已在前面逻辑中确定
               applyReason: payload.applyReason
           }
          await applicationStore.createApplication(createPayload)
          ElMessage.success('申请添加成功')
        } else {
             console.error("提交表单状态错误：isEdit 为 true 但 id 缺失");
             ElMessage.error("提交失败，请重试");
             return;
        }
        formDialogVisible.value = false
        await fetchApplications() // 刷新列表
        await fetchMaterials() // 刷新物资列表（可能影响库存显示）
      } catch (error) {
        // Store 中已处理 ElMessage
        console.error("submitForm error:", error)
      }
    } else {
      console.log('表单校验失败')
      return false
    }
  })
}

// 提交审核表单
const submitReview = async () => {
  if (!reviewFormRef.value) return
  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
        // 确认审核人ID
        if (!currentUserId.value) {
            ElMessage.error("无法获取当前用户信息，请重新登录后尝试");
            return;
        }
        reviewForm.value.reviewerId = currentUserId.value; // 再次确保审核人ID正确
      try {
        await applicationStore.reviewApplication(reviewForm.value)
        ElMessage.success('审核操作成功')
        reviewDialogVisible.value = false
        await fetchApplications() // 刷新列表
      } catch (error) {
        // Store 中已处理 ElMessage
        console.error("submitReview error:", error)
      }
    } else {
      console.log('审核表单校验失败')
      return false
    }
  })
}

// 处理删除申请
const handleDeleteApplication = async (id: number, status: string) => {
   if (status !== '待审核') {
     ElMessage.warning('只能删除状态为 "待审核" 的申请')
     return
   }
  try {
    await ElMessageBox.confirm('确定删除此物资申请吗？', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await applicationStore.deleteApplication(id)
    ElMessage.success('申请删除成功')
    // fetchApplications 会在 store action 中调用
  } catch (error: any) {
    if (error !== 'cancel') { // 忽略取消操作的 'cancel' 错误
      // Store 中已处理 ElMessage
      console.error("handleDeleteApplication error:", error)
    } else {
      ElMessage.info('取消删除')
    }
  }
}

// 重置添加/编辑表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    materialId: null,
    quantity: 1,
    applicantId: isAdmin.value ? null : currentUserId.value,
    applyReason: '',
  }
  currentApplication.value = null // 清除当前行记录
}

// 重置审核表单
const resetReviewForm = () => {
  if (reviewFormRef.value) {
    reviewFormRef.value.resetFields()
  }
  reviewForm.value = {
    id: 0,
    reviewerId: currentUserId.value, // 保持当前用户ID
    status: '', // 清空状态
    reviewComments: '', // 清空评论
  }
   // 不清除 currentApplication，因为审核弹窗依赖它显示信息
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case '待审核': return 'warning'
    case '通过': return 'success'
    case '未通过': return 'danger'
    default: return 'info'
  }
}

// --- Lifecycle Hooks ---
onMounted(async () => {
  // 并行获取初始数据
  await Promise.all([
    fetchApplications(),
    fetchMaterials(),
    fetchEmployees() // 获取员工列表
  ])
})

</script>

<style scoped>
.application-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px; /* 根据 TopBar 高度调整 */
  width: 90%; /* 适当加宽以容纳更多列 */
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
  /* 修改：让按钮默认在左侧 */
  display: flex;
  justify-content: flex-start;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 调整表格按钮间距 */
.el-table .el-button + .el-button {
  margin-left: 8px;
}

.el-tag {
  cursor: default;
}

.dialog-footer {
  text-align: right;
}

/* 调整 InputNumber 样式 */
.el-input-number {
  text-align: left;
}
</style>